import { Form, Button, Modal, Input, Space, Select, Row, Col, Tabs } from 'antd';
import { useEffect, useState } from 'react';
import { CompanyForm, ReportTable, SearchBar, TreeSection, ReportTreeSection } from './components';
import MergeModal from './components/MergeModal';
import { reportTreeData } from './constants/data';
import { TabItem } from './types';
import { useModel } from 'umi';
import { getAllTreeKeys } from './utils/treeUtils';
import { getCompanyTreeData,getTemplate,companyTreeStructure } from '@/services/cpasRequest';
import ApprovedFinance from './approvedFinance';
import Annotations from './tab1'; 
import AdjustContextData from '../adjustComponent';
import InternalTran from '../internalTran';
import TrialBalance from '../trialBalance';
import OpeningCheck from '../openingCheck';
import FinancialStatementsCheck from '../financialStatementsCheck';
import AudTabPage from '@/components/PageTab/AudTabPage';
 


// 递归转换公司树数据以匹配 antd Tree 组件的格式
const transformCompanyTreeData = (nodes: any[]): any[] => {
  return nodes.map((node) => ({
    title: node.currentCompany, // 使用 currentCompany 作为显示名称
    key: `company-${node.currentCompany}`, // 使用 currentCompanyUscc 作为 key
    bsdwxydms: node.currentCompanyUscc, // 添加 bsdwxydms 字段
    mergeType: node.mergeType, 
    children: node.children ? transformCompanyTreeData(node.children) : [],
  }));
};

export default function Layout() {

  
    const { initialState } = useModel('@@initialState');
    const { dbname,bsdw } = initialState?.curPart as API.CurPart;


  const [selectedKeys, setSelectedKeys] = useState<string[]>([]);
  const [searchValue, setSearchValue] = useState('');
  const [leftActiveTab, setLeftActiveTab] = useState('tree');
  const [rightContentType, setRightContentType] = useState('default'); // 'default', 'report', 'company'
  const [expandedKeys, setExpandedKeys] = useState<string[]>([]);
  // 为右侧填报内容树形结构创建独立的状态
  const [reportSelectedKeys, setReportSelectedKeys] = useState<string[]>([]);
  const [reportExpandedKeys, setReportExpandedKeys] = useState<string[]>([]);
  const [companyTreeData, setCompanyTreeData] = useState<any[]>([]);
  const [mergeModalVisible, setMergeModalVisible] = useState(false);
  const [preSelectedKeys, setPreSelectedKeys] = useState<string[]>([]);
  const [createTreeModalVisible, setCreateTreeModalVisible] = useState(false);
  const [activeTabKey, setActiveTabKey] = useState('1'); // 添加活跃tab状态
  const [approvedFinanceKey, setApprovedFinanceKey] = useState(0); // 用于强制重新挂载ApprovedFinance组件
  const [companyFormKey, setCompanyFormKey] = useState(0); // 用于强制重新挂载CompanyForm组件
  const [annotationsKey, setAnnotationsKey] = useState(0); // 用于强制重新挂载Annotations组件
  const [adjustKey, setAdjustKey] = useState(0); // 用于强制重新挂载AdjustContextData组件
  const [internalTranKey, setInternalTranKey] = useState(0); // 用于强制重新挂载InternalTran组件
  const [trialBalanceKey, setTrialBalanceKey] = useState(0); // 用于强制重新挂载TrialBalance组件
  const [openingCheckKey, setOpeningCheckKey] = useState(0); // 用于强制重新挂载OpeningCheck组件
  const [financialStatementsCheckKey, setFinancialStatementsCheckKey] = useState(0); // 用于强制重新挂载FinancialStatementsCheck组件

  const [form] = Form.useForm();
  const [createTreeForm] = Form.useForm();

  const [bsdwxydm, setBsdwxydm] = useState('');
  const [selectedNodeBsdwxydms, setSelectedNodeBsdwxydms] = useState('');
  const [mergeNode, setMergeNode] = useState(0);

  


  const onTreeSelect = (selectedKeys: any, info: any) => {
    setSelectedKeys(selectedKeys);
    if (selectedKeys.length > 0) {
      // 左键点击时显示公司信息
      setRightContentType('company');
      // 自动切换到第一个tab（公司信息）
      setActiveTabKey('1');
      // 如果是公司数据，设置表单值
      if (selectedKeys[0].startsWith('company-')) {
        form.setFieldsValue({
          companyName: info.selectedNodes[0]?.title || '',
        });
        
        // 获取选中节点的bsdwxydms和mergeType并保存到全局
        const selectedNode = info.selectedNodes[0];
        if (selectedNode && selectedNode.bsdwxydms) {
          const audTabPage = AudTabPage.getInstance();
          audTabPage.setGlobalBsdwxydms(selectedNode.bsdwxydms);
        }
        if (selectedNode) {
          const audTabPage = AudTabPage.getInstance();
          audTabPage.setGlobalMergeType(selectedNode.mergeType);
        }
      }
    } else {
      setRightContentType('default');
    }
  };

  // 当切换tab时，更新展开的keys
  const handleTabChange = (activeKey: string) => {
    setLeftActiveTab(activeKey);
    const currentData = activeKey === 'report' ? reportTreeData : companyTreeData;
    setExpandedKeys(getAllTreeKeys(currentData));
  };



  // 处理树节点展开/收起
  const handleTreeExpand = (expandedKeys: any[]) => {
    setExpandedKeys(expandedKeys as string[]);
  };

  // 处理右侧填报内容树的选择
  const handleReportTreeSelect = (selectedKeys: any, info: any) => {
    setReportSelectedKeys(selectedKeys);
  };

  // 从TreeSection选中的key中提取xydm
  const getSelectedXydm = () => {
    if (selectedKeys.length > 0 && selectedKeys[0].startsWith('company-')) {
      console.log("🚀 ~ getSelectedXydm ~ selectedKeys[0].replace('company-', ''):", selectedKeys[0].replace('company-', ''))
      return selectedKeys[0].replace('company-', '');
    }
    return '';
  };

  // 从ReportTreeSection选中的key中提取title
  const getSelectedReportTitle = () => {
    if (reportSelectedKeys.length > 0) {
      // 从reportTreeData中找到对应的title
      const findTitle = (data: any[], key: string): string => {
        for (const item of data) {
          if (item.key === key) {
            return item.title;
          }
          if (item.children) {
            const childTitle = findTitle(item.children, key);
            if (childTitle) return childTitle;
          }
        }
        return '';
      };
      return findTitle(reportTreeData, reportSelectedKeys[0]);
    }
    return '';
  };

  // 处理右侧填报内容树的展开/收起
  const handleReportTreeExpand = (expandedKeys: any[]) => {
    setReportExpandedKeys(expandedKeys as string[]);
  };

  // 处理右键菜单点击
  const handleContextMenuAction = (action: string, nodeData: any, preSelected?: string[], actionType?: string) => {
    console.log('右键菜单操作:', action, '节点数据:', nodeData, '预选中节点:', preSelected, '操作类型:', actionType);
    
    switch (action) {
      case 'merge':
        // 处理合并报表操作 - 显示合并弹窗
        if (preSelected && preSelected.length > 0) {
          setPreSelectedKeys(preSelected);
        } else {
          setPreSelectedKeys([]);
        }
        
        // 设置选中节点的bsdwxydms
        if (nodeData && nodeData.bsdwxydms) {
          setSelectedNodeBsdwxydms(nodeData.bsdwxydms);
        }
        
        // 根据操作类型设置mergeNode值
        if (actionType === 'summaryDirect') {
          setMergeNode(0); // 节点汇总直接下级
        } else if (actionType === 'summaryAll') {
          setMergeNode(1); // 节点汇总所有下级
        }
        
        setMergeModalVisible(true);
        break;
      case 'report':
        // 处理填报内容操作 - 右侧显示树形结构和ReportTable组件
        setRightContentType('report');
        break;
      default:
        break;
    }
  };

  // 处理合并弹窗取消
  const handleMergeModalCancel = () => {
    setMergeModalVisible(false);
  };

  // 处理合并弹窗确认
  const handleMergeModalConfirm = (selectedKeys: string[]) => {
    console.log('合并确认，选中的节点:', selectedKeys);
    // 这里可以添加具体的合并逻辑
    setMergeModalVisible(false);
  };

  // 初始化时设置默认展开的keys
  useEffect(() => {
    // 每次组件挂载时都重置状态并显示公司信息
    
    if (leftActiveTab === 'tree' || leftActiveTab === 'list') {
      // 原有接口调用代码（已注释）
          getTemplate(bsdw).then((ress) => {
            if(ress.data){  
              setBsdwxydm(ress.data.bsdwxydm); 
              getCompanyTreeData(ress.data.bsdwxydm).then((res) => { 
                if (res.status === 'success' && res.data) {
                  // @ts-ignore
                  const transformedData = transformCompanyTreeData(res.data);
                  setCompanyTreeData(transformedData);
                  setExpandedKeys(getAllTreeKeys(transformedData));
                }
              });
            } 
          }) 
      // 默认选中第一个公司节点，显示公司信息
    } else if (leftActiveTab === 'report') {
      setExpandedKeys(getAllTreeKeys(reportTreeData));
    }
    // 初始化右侧填报内容树的展开状态
    setReportExpandedKeys(getAllTreeKeys(reportTreeData));
  }, [leftActiveTab]);
 

  const renderRightContent = () => {
    switch (rightContentType) {
      case 'company':
        // 左键点击某一项时显示公司信息
        return   (
          <div style={{ height: '100%' }}>
            <Tabs
              defaultActiveKey="1"
              activeKey={activeTabKey}
              onChange={(key) => {
                setActiveTabKey(key);
                // 每次切换tab时，强制重新挂载对应的组件
                switch(key) {
                  case '1':
                    setCompanyFormKey(prev => prev + 1);
                    break;
                  case '2':
                    setApprovedFinanceKey(prev => prev + 1);
                    break;
                  case '3':
                    setAnnotationsKey(prev => prev + 1);
                    break;
                  case '4':
                    setAdjustKey(prev => prev + 1);
                    break;
                  case '5':
                    setInternalTranKey(prev => prev + 1);
                    break;
                  case '6':
                    setTrialBalanceKey(prev => prev + 1);
                    break;
                  case '7':
                    setOpeningCheckKey(prev => prev + 1);
                    break;
                  case '8':
                    setFinancialStatementsCheckKey(prev => prev + 1);
                    break;
                }
              }}
              items={[
                {
                  key: '1', 
                  label: '公司信息',
                  children: <CompanyForm key={`company-form-${companyFormKey}`} form={form} />
                },{
                  key: '2',
                  label: '审定财务报表',
                  children: <ApprovedFinance key={`approved-finance-${approvedFinanceKey}`} />
                },
                {
                  key: '3', 
                  label: '附注与分析',
                  children: <Annotations key={`annotations-${annotationsKey}`} />
                },
                {
                  key: '4',
                  label: '审计调整',
                  children: <AdjustContextData key={`adjust-${adjustKey}`} whereFrom="审计调整" />

                },
                {
                  key: '5',
                  label: '内部往来统计',
                  children: <InternalTran key={`internal-tran-${internalTranKey}`} /> 
                },
                {
                  key: '6',
                  label: '合并抵消分录',
                  children: <TrialBalance key={`trial-balance-${trialBalanceKey}`} /> 
                },
                {
                  key: '7',
                  label: '期初报表核对',
                  children: <OpeningCheck key={`opening-check-${openingCheckKey}`} /> 
                },
                {
                  key: '8',
                  label: '财务报表核对',
                  children: <FinancialStatementsCheck key={`financial-statements-check-${financialStatementsCheckKey}`} /> 
                }
              ]}
            />
          </div>
        )
        // <CompanyInfo form={form} />;
        
      default:
        // 默认状态
        return (
          <div
            style={{
              display: 'flex',
              justifyContent: 'center',
              alignItems: 'center',
              height: '100%',
              color: '#999',
            }}
          >
            请从左侧选择查看内容
          </div>
        );
    }
  };

  return (
    <div
      style={{
        display: 'flex',
        height: '95vh',
        fontFamily: 'Microsoft YaHei, Arial, sans-serif',
        fontSize: '12px',
        background: '#fff',
      }}
    >

      <div
        style={{
          width: '280px',
          paddingTop: '16px',

          display: 'flex',
          flexDirection: 'column',
        }}
      >
        {/* <SearchBar searchValue={searchValue} onChange={setSearchValue} /> */}
        <div style={{ padding: '16px 0', borderBottom: '1px solid #f0f0f0' }}>
          <Space style={{ width: '100%' }}>
            <Button 
              type="primary" 
              style={{ flex: 1 }}
              onClick={() => setCreateTreeModalVisible(true)}
            >
              新建树形
            </Button>

          </Space>
        </div>
        <TreeSection
          title="所有单位"
          treeData={companyTreeData}
          selectedKeys={selectedKeys}
          expandedKeys={expandedKeys}
          onSelect={onTreeSelect}
          onExpand={handleTreeExpand}
          onContextMenuAction={handleContextMenuAction}
          className="main-company-tree-section"
        />
        {/* <Tabs
          activeKey={leftActiveTab}
          onChange={handleTabChange}
          items={leftTabItems}
          size="small"
        /> */}
      </div>

      <div
        style={{
          flex: 1,
          background: '#ffffff',
          padding: '16px',
          overflow: 'scroll',
        }}
      >
        {renderRightContent()}
      </div>
      
      {/* 合并报表弹窗 */}
      <MergeModal
        visible={mergeModalVisible}
        onCancel={handleMergeModalCancel}
        onConfirm={handleMergeModalConfirm}
        treeData={companyTreeData}
        preSelectedKeys={preSelectedKeys}
      />
      
      {/* 新建树形弹窗 */}
      <Modal
        title="新建树形"
        open={createTreeModalVisible}
        onCancel={() => {
          setCreateTreeModalVisible(false);
          createTreeForm.resetFields();
        }}
        onOk={() => {
          createTreeForm.validateFields().then(async values => {
            console.log('新建树形:', values);
            
            // 转换表单数据为接口参数格式
            const params = {
              auditCompanyUscc: bsdwxydm, // 本企业信用代码 
              currentCompany: values.companyName, // 本企业名称
              currentCompanyUscc: values.creditCode, // 本企业信用代码
              higherCompany: values.parentCompanyName, // 上级企业名称
              higherCompanyUscc: values.parentCreditCode, // 上级企业信用代码
              blocCompany: values.groupCompanyName, // 集团企业名称
              blocCompanyUscc: values.groupCreditCode, // 集团企业信用代码
              reportType: values.reportType === 'state-owned' ? 0 : 1 // 国企是0，上市是1
            };
            
            try {
              // 调用接口
              const result = await companyTreeStructure(params);
              console.log('创建树形结构成功:', result);
              
              setCreateTreeModalVisible(false);
              createTreeForm.resetFields();
              
              // 刷新树形数据
              getTemplate(bsdw).then((ress) => {
                if(ress.data){  
                  getCompanyTreeData(ress.data.bsdwxydm).then((res) => { 
                    if (res.status === 'success' && res.data) {
                      // @ts-ignore
                      const transformedData = transformCompanyTreeData(res.data);
                      setCompanyTreeData(transformedData);
                      setExpandedKeys(getAllTreeKeys(transformedData));
                    }
                  });
                } 
              })
              
            } catch (error) {
              console.error('创建树形结构失败:', error);
              // 可以在这里添加错误处理，比如显示错误提示
            }
          });
        }}
        okText="确定"
        cancelText="取消"
      >
        <Form form={createTreeForm} layout="vertical" size='large'>
          <Row gutter={16}>
            <Col span={12}>
              <Form.Item
                label="本企业名称"
                name="companyName"
                rules={[{ required: true, message: '请输入本企业名称' }]}
              >
                <Input placeholder="请输入本企业名称" />
              </Form.Item>
            </Col>
            <Col span={12}>
              <Form.Item
                label="本企业信用代码"
                name="creditCode"
                rules={[{ required: true, message: '请输入本企业信用代码' }]}
              >
                <Input placeholder="请输入本企业信用代码" />
              </Form.Item>
            </Col>
          </Row>
          <Row gutter={16}>
            <Col span={12}>
              <Form.Item
                label="上级企业名称"
                name="parentCompanyName"
                rules={[{ required: true, message: '请输入上级企业名称' }]}
              >
                <Input placeholder="请输入上级企业名称" />
              </Form.Item>
            </Col>
            <Col span={12}>
              <Form.Item
                label="上级企业信用代码"
                name="parentCreditCode"
                rules={[{ required: true, message: '请输入上级企业信用代码' }]}
              >
                <Input placeholder="请输入上级企业信用代码" />
              </Form.Item>
            </Col>
          </Row>
          <Row gutter={16}>
            <Col span={12}>
              <Form.Item
                label="集团企业名称"
                name="groupCompanyName"
                rules={[{ required: true, message: '请输入集团企业名称' }]}
              >
                <Input placeholder="请输入集团企业名称" />
              </Form.Item>
            </Col>
            <Col span={12}>
              <Form.Item
                label="集团企业信用代码"
                name="groupCreditCode"
                rules={[{ required: true, message: '请输入集团企业信用代码' }]}
              >
                <Input placeholder="请输入集团企业信用代码" />
              </Form.Item>
            </Col>
          </Row>
          <Row gutter={16}>
            <Col span={12}>
              <Form.Item
                label="报表类型"
                name="reportType"
                rules={[{ required: true, message: '请选择报表类型' }]}
              >
                <Select placeholder="请选择报表类型">
                  <Select.Option value="state-owned">国企</Select.Option>
                  <Select.Option value="listed">上市</Select.Option>
                </Select>
              </Form.Item>
            </Col>
          </Row>
        </Form>
      </Modal>
      

    </div>
  );
}
